<template>
   <div>
     <breadcrumb></breadcrumb>
      <el-row style="margin:10px 0px">
            <el-col :span="3">
                <el-select v-model="query.searchType">
                    <el-option v-for="item in options" 
                        :key="item.label"
                        :value="item.value" 
                        :label="item.label">
                    </el-option>
                </el-select>
            </el-col>
            <el-col :span="5">
                 <el-input placeholder="请输入要搜索内容" v-model="query.searchValue"></el-input>
            </el-col>
            <el-col :span="3">
                <el-button type="primary" icon="el-icon-search">搜索</el-button>
            </el-col>
            <el-col :span="6">
                <el-button type="primary" @click="openAddDialog">增加学生</el-button>
            </el-col>
      </el-row>
     
      <el-table :data="rows" stripe border row-key="_id">
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="age" label="年龄" align="center"></el-table-column>
        <el-table-column prop="image" label="头像" align="center">
            <template slot-scope="scope">
                <el-avatar :src="scope.row.image"></el-avatar>
            </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" align="center">
             <template slot-scope="scope">
                <el-tag v-if="scope.row.gender==='男'">{{scope.row.gender}}</el-tag>
                <el-tag v-if="scope.row.gender==='女'" type="danger">{{scope.row.gender}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="subjectsId.name" label="专业" align="center"></el-table-column>
        <el-table-column prop="classesId.name" label="班级" align="center"></el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
               <!-- <router-link :to="`/home/studentdetail?id=${scope.row._id}`" class="oper">详情</router-link>
               <router-link :to="`/home/studentModify/${scope.row._id}/${scope.row.name}`" class="oper">修改</router-link> 
               <router-link :to="{name:'sxxq',query:{id:scope.row._id}}" class="oper">详情</router-link>
               <router-link :to="{name:'sxxg',params:{sid:scope.row._id,sname:scope.row.name}}">修改</router-link> -->
               <el-button type="primary" @click="goDetail(scope.row._id)">详情</el-button>
               <el-button type="success" @click="goModify(scope.row._id,scope.row.name)">修改</el-button>
            </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination 
        background
        :total="total"
        :page-size="query.pageSize"
        :current-page="query.currentPage"
        layout="sizes,prev, pager, next, jumper, ->, total" 
        :page-sizes="[3,5,10,15,20]" 
        @current-change="currentChangeHandle"
        @size-change="sizeChangeHandle"></el-pagination>

       <!--增加学生的模态框-->
       <el-dialog title="增加学生" :visible.sync="dialogVisible" width="600px">
            <div>
                <el-form label-width="60px" :rules="rules" :model="addStudentForm" ref="addRuleForm">
                    <el-form-item label="姓名:" prop="name">
                        <el-input v-model="addStudentForm.name"></el-input>
                    </el-form-item>
                     <el-form-item label="年龄:" prop="age">
                        <el-input v-model="addStudentForm.age"></el-input>
                    </el-form-item>
                    <el-form-item label="性别:">
                        <el-radio-group v-model="addStudentForm.gender">
                            <el-radio label="男">男</el-radio>
                            <el-radio label="女">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="专业" prop="subjectsId">
                        <el-select v-model="addStudentForm.subjectsId">
                            <el-option 
                                v-for="item in subjects" 
                                :key="item._id"
                                :label="item.name"
                                :value="item._id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="班级">
                        <el-select v-model="addStudentForm.classesId">
                            <el-option 
                                v-for="item in classesList" 
                                :key="item._id"
                                :label="item.name"
                                :value="item._id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                   <el-form-item label="头像">
                      <el-upload 
                         :show-file-list="false"
                         class="avatar-uploader"
                         :action="`${baseUrl}/upload/uploadImage`"
                         name="avatar"
                         :before-upload="beforeAvatarUpload"
                         :on-success="handleAvatarSuccess">
                         <img :src="addStudentForm.image" v-if="addStudentForm.image" class="avatar"/>
                         <i class="el-icon-plus avatar-uploader-icon" v-else></i>
                      </el-upload>
                   </el-form-item>
                </el-form>
            </div>
            <div slot="footer">
                <el-button type="primary" @click="addStudent('addRuleForm')">确认</el-button>
                <el-button @click="resetInfo">重置</el-button>
            </div>
       </el-dialog>

   </div>
</template>

<script>
export default {
    data(){
        /**验证年龄的函数 */
       const validateAge=(rule, value, callback)=>{
         var ageReg=/^120$|^[1-9]$|^(1[0-1]|[1-9])\d$/
         if(!ageReg.test(value)){
            return callback(new Error('年龄格式不正确'))
         }
         //正确后放行，执行后续的逻辑操作
         callback()
        
       }
        return{
            baseUrl:process.env.VUE_APP_BASE_URL,
            rules:{
                name:[
                    {required:true,message:'请输入用户名',trigger:'blur'},
                    {min:3,max:6,message:'姓名长度3-6位',trigger:'blur'}
                ],
                age:[
                    {required:true,message:'年龄不能为空',trigger:'blur'},
                    {validator:validateAge,trigger:'blur'}
                ]
            },
            rows:[],
            total:0,
            query:{
                 pageSize:5,
                 currentPage:1,
                 searchType:'',
                 searchValue:'',
            },
            options:[
                {label:'姓名',value:'name'},
                {label:'性别',value:'gender'},
                {label:'电话',value:'phone'}
            ],
            dialogVisible:false,
            subjects:[],
            classesList:[],
            addStudentForm:{
                name:'',
                age:'',
                gender:'男',
                image:'',
                subjectsId:'',
                classesId:''
            }
        }
    },
    methods:{
        goModify(sid,sname){
           //this.$router.push(`/home/studentModify/${sid}/${sname}`)
           this.$router.push({
            name:'sxxg',
            params:{
                sid,sname
            }
           })
        },
        goDetail(id){
        this.$router.push(`/home/studentdetail?id=${id}`)
        //    this.$router.push({
        //      path:'/home/studentdetail',
        //      query:{
        //         id
        //      }
        //    })
        // this.$router.push({
        //     name:'sxxq',
        //     query:{id}
        // })
        },
        sizeChangeHandle(arg){
            this.pageSize=arg
            this.getStudents()
        },
        currentChangeHandle(arg){
            this.currentPage=arg
            this.getStudents()
        },
        async getStudents(){
            let params={
                pageSize:this.pageSize,
                currentPage:this.currentPage
            }
            const result=await this.$api.students.getStudentsApi(params)
            console.log('result',result);
            this.rows=result.data.result
            this.total=result.data.total
        },
        openAddDialog(){
            this.getSubjects()
            this.dialogVisible=true
        },
        async getSubjects(){
            const result=await this.$api.subjects.getSubjectsApi()
            this.subjects=result.data.result
        },
        addStudent(arg){
            this.$refs.addRuleForm.validate(async(valid)=>{
                console.log('valid',valid);
                if(valid){
                   const result=await this.$api.students.addStudentApi(this.addStudentForm)
                        if(result.code){
                        this.$message.success(result.message)
                        this.dialogVisible=false
                        this.getStudents()
                    }
                }else{
                    this.$message.error('请检查表单信息正确后再提交')
                }
            })           
        },
        resetInfo(){
            //重置表单元素
           this.$refs.addRuleForm.resetFields()
        },
        beforeAvatarUpload(file){
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        handleAvatarSuccess(res){
           this.addStudentForm.image=`${process.env.VUE_APP_BASE_URL}${res.avatarPath}`
        }
    },
    watch:{
        async 'addStudentForm.subjectsId'(newval){
            const result=await this.$api.classes.getClassesBySubjectsIdApi(newval)
            if(!result.code){
                this.addStudentForm.classesId=""
            }else{
                this.classesList=result.data.result 
            }
           
        }
    },
    created(){
        this.getStudents()
    }
}
</script>

<style lang="scss" scoped>
  .avatar-uploader{
    ::v-deep & .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
     ::v-deep & .el-upload:hover {
        border-color: #409EFF;
    }
   
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .oper{
    margin: 10px;
  }
</style>